import { _decorator, Component, director, EditBox } from 'cc'
import { ApiMsgEnum } from '../Common'
import { SceneEnum } from '../Enum'
import DataManager from '../Global/DataManager'
import { NetworkManager } from '../Global/NetworkManager'
const { ccclass } = _decorator

@ccclass('LoginManager')
export class LoginManager extends Component {
  input: EditBox

  onLoad() {
    this.input = this.getComponentInChildren(EditBox)
    // 预加载场景，避免切换场景时卡顿
    director.preloadScene(SceneEnum.Hall)
  }

  async start() {
    await NetworkManager.Instance.connect()
  }

  async handleClick() {
    if (!NetworkManager.Instance.isConnected) {
      console.log('未连接！')
      await NetworkManager.Instance.connect()
      return
    }

    const nickname = this.input.string
    if (!nickname) {
      console.log('昵称不能为空！')
      return
    }

    const { success, res, error } = await NetworkManager.Instance.callApi(ApiMsgEnum.ApiPlayerJoin, { nickname })
    if (!success) {
      console.log(error)
      return
    }

    DataManager.Instance.myPlayerId = res.player.id

    director.loadScene(SceneEnum.Hall)
  }
}
